#include "Triangle.h"

Triangle::Triangle()
{
	LOGIDBG("Init Triangle\n");
}

Triangle::~Triangle()
{
	LOGIDBG("Destroy Triangle\n");
}

FWint Triangle::Init()
{
	FWint err = 0;
	_Mesh = new Mesh(1, "Resources\\Meshes\\", "Triangle.snk");
	err += _Mesh->Init();

	_Texture = new Texture();
	char * tex = StringHelper::SumString(BASE_SRC_PATH, "Resources\\Textures\\Dirt.tga");
	err += _Texture->Init(1, &tex);
	SAFE_DEL_ARRAY(tex);

	_Shader = new Shader(2, "Resources\\Shaders\\", "Triangle.vsh;Triangle.fsh");
	err += _Shader->Init();
	return err;
}

void Triangle::Destroy()
{
	_Mesh->Destroy();
	_Texture->Destroy();
	_Shader->Destroy();
}

void Triangle::Update(FWfloat deltaTime)
{

}

void Triangle::Draw()
{
	glUseProgram(_Shader->ProgramObject);

	if (_Shader->Samplers[0] != -1)
	{
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, _Texture->TBOs[0]);
		glUniform1i(_Shader->Samplers[0], 0);
	}

	glBindBuffer(GL_ARRAY_BUFFER, _Mesh->VBOs[0]);

	if (_Shader->Position != -1)
	{
		glEnableVertexAttribArray(_Shader->Position);
		glVertexAttribPointer(_Shader->Position, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if (_Shader->Coordinate != -1)
	{
		glEnableVertexAttribArray(_Shader->Coordinate);
		glVertexAttribPointer(_Shader->Coordinate, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3));
	}
	if (_Shader->MatrixWVP != -1)
	{
		Matrix WVP = Matrix().SetIdentity() * Global::CurrentCamera->View*Global::CurrentCamera->Projection;
		glUniformMatrix4fv(_Shader->MatrixWVP, 1, GL_FALSE, (FWfloat*)&WVP);
	}

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _Mesh->IBOs[0]);
	glDrawElements(GL_TRIANGLES, _Mesh->IBOCount, GL_UNSIGNED_INT, 0);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, _Texture->TBOs[0]);
}